package com.kaiwukj.android.ufamily.mvp.ui.page.service.detail;

import android.util.SparseBooleanArray;
import android.widget.CheckedTextView;

import androidx.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.ServiceResult;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public class ServiceAppointmentAdapter extends BaseQuickAdapter<ServiceResult.ServiceInfo, BaseViewHolder> {


    private SparseBooleanArray sparseBooleanArray;
    private int lastCheckedPosition = -1;


    public ServiceAppointmentAdapter(@Nullable List<ServiceResult.ServiceInfo> data) {
        super(R.layout.item_service_appointment_project, data);
        sparseBooleanArray = new SparseBooleanArray();
    }

    public void checkItem(int position) {
        if (lastCheckedPosition == position) return;
        if (lastCheckedPosition != -1) {
            sparseBooleanArray.put(lastCheckedPosition, false);
            notifyItemChanged(lastCheckedPosition);
        }
        lastCheckedPosition = position;
        sparseBooleanArray.put(lastCheckedPosition, true);
        notifyItemChanged(lastCheckedPosition);
        if (mOnCheckChangedListener != null) mOnCheckChangedListener.onChecked(lastCheckedPosition);
    }

    public ServiceResult.ServiceInfo getCheckedItem() {
        return getItem(lastCheckedPosition);
    }

    @Override
    protected void convert(@NotNull BaseViewHolder holder, ServiceResult.ServiceInfo result) {
        CheckedTextView tvText = holder.getView(R.id.tv_text);
        tvText.setText(result.getParameterName());
        tvText.setChecked(sparseBooleanArray.get(holder.getAdapterPosition()));
        holder.itemView.setOnClickListener(v -> checkItem(holder.getAdapterPosition()));
    }

    private OnCheckChangedListener mOnCheckChangedListener;

    public void setOnCheckChangedListener(OnCheckChangedListener onCheckChangedListener) {
        mOnCheckChangedListener = onCheckChangedListener;
    }

    public interface OnCheckChangedListener {
        void onChecked(int position);
    }
}
